package user

import (
	"chaowan/data_source"
	"chaowan/models"
	"chaowan/service"
	"chaowan/utils"
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
	"time"
)

type FanshangsRBody struct {
	Data       []models.Fanshang `json:"data"`
	PageNo     int               `json:"pageNo"`
	PageSize   int               `json:"pageSize"`
	TotalCount int64             `json:"totalCount"`
	TotalPage  int64             `json:"totalPage"`
}

type FanshangsBody struct {
	Page     int    `json:"page"`
	Pagesize int    `json:"pagesize"`
	Classify int64  `json:"classify" gorm:"classify"` // 1付钱 2付积分
	Status   int64  `json:"status" gorm:"status"`     // 1一番赏 2福利屋
	Uid      int64  `json:"uid" gorm:"uid"`
	Qudao    string `json:"qudao"`
}

func Fanshangs(ctx *gin.Context) {
	request := FanshangsBody{}
	ctx.ShouldBind(&request)
	classify := request.Classify
	status := request.Status
	currentPage := request.Page
	pageSize := request.Pagesize
	uid := request.Uid
	offsetNum := pageSize * (currentPage - 1)

	qudao := request.Qudao
	var qudaos []models.Qudao
	qudaos = service.Qudaolist()
	var qudaoid int64
	for _, q := range qudaos {
		if qudao == q.Value {
			qudaoid = q.ID
		}
	}
	var fanshangidarrs []int64
	if qudaoid > 0 {
		var zhuanpanqudaos []models.Zhuanpanqudao
		data_source.Db.Where("state = 1").Where("qudaoid = ?", qudaoid).Find(&zhuanpanqudaos)
		for _, z := range zhuanpanqudaos {
			fanshangidarrs = append(fanshangidarrs, z.Otherid)
		}
	}

	var count int64
	var users []models.Fanshang
	res := data_source.Db.Where("status = 1").Debug()
	if len(fanshangidarrs) > 0 {
		res = res.Where("id not in (?)", fanshangidarrs)
	}
	if uid > 0 {
		var fanshangs []models.Fanshangsql
		fanshangs = service.Fanshangxianshou()
		var fanshangidarr []int64
		var fanshangorder []models.Orderfanshangfk
		data_source.Db.Model(&models.Orderfanshang{}).Where("uid = ?", uid).Find(&fanshangorder)
		inttime, endtime := getCurrentdayStartAndEnd()
		for _, n := range fanshangs {
			var usernum int64
			var daynum int64
			for _, no := range fanshangorder {
				if no.Fanshangid == n.ID {
					usernum = usernum + no.Num
					if no.Addtime >= inttime && no.Addtime < endtime {
						daynum = daynum + no.Num
					}
				}
			}
			if usernum >= n.Usernum {
				fanshangidarr = append(fanshangidarr, n.ID)
			}
			if daynum >= n.Daynum {
				fanshangidarr = append(fanshangidarr, n.ID)
			}
		}
		res = res.Where("id not in (?)", fanshangidarr)
	}

	if classify > 0 {
		res = res.Where("classify = ?", classify)
	}
	if status > 0 {
		if status == 1 {
			res = res.Where("liushui = 0")
		}
		if status == 2 {
			res = res.Where("classify = 2 or (classify = 1 and liushui > 0)")
		}
	}
	res.Model(&models.Fanshang{}).Count(&count)
	res.Limit(pageSize).Offset(offsetNum).Order("sort asc,id desc").Find(&users)

	var totalPage int64
	mo := count % int64(pageSize)
	if mo > 0 {
		totalPage = count/int64(pageSize) + 1
	} else {
		totalPage = count / int64(pageSize)
	}
	data := FanshangsRBody{
		Data:       users,
		PageNo:     currentPage,
		PageSize:   pageSize,
		TotalCount: count,
		TotalPage:  totalPage,
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    data,
		"msg":     "ok",
	})
	return
}
func Fanshanginfo(ctx *gin.Context) {
	request := GoodsBody{}
	ctx.ShouldBind(&request)
	id := request.ID
	uid := request.Uid
	qudao := request.Qudao
	var qudaos []models.Qudao
	qudaos = service.Qudaolist()
	var qudaoid int64
	for _, q := range qudaos {
		if qudao == q.Value {
			qudaoid = q.ID
		}
	}

	var zhuanpanqudaos models.Zhuanpanqudao
	data_source.Db.Where("state = 1").Where("qudaoid = ?", qudaoid).Where("otherid = ?", id).First(&zhuanpanqudaos)
	if zhuanpanqudaos.ID > 0 {
		ctx.JSON(http.StatusOK, gin.H{
			"code":    400,
			"error":   1,
			"success": 400,
			"data":    "on",
			"msg":     "该赏品已下架",
		})
		return
	}

	var good models.Fanshang
	data_source.Db.Where("id = ?", id).First(&good)
	if good.Status == 2 {
		ctx.JSON(http.StatusOK, gin.H{
			"code":    400,
			"error":   1,
			"success": 400,
			"data":    "on",
			"msg":     "该赏品已下架",
		})
		return
	}
	var collect models.Collect
	data_source.Db.Where("goodid = ?", id).Where("uid = ?", uid).Where("state = 3").First(&collect)
	good.Collect = 1
	if collect.ID > 0 {
		good.Collect = 2
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    good,
		"msg":     "ok",
	})
	return
}
func Fanshangcollect(ctx *gin.Context) {
	request := GoodsBody{}
	ctx.ShouldBind(&request)
	id := request.ID
	uid := request.Uid
	if uid == 0 {
		ctx.JSON(http.StatusOK, gin.H{
			"code":    101,
			"error":   1,
			"success": 400,
			"data":    "on",
			"msg":     "请登录",
		})
		return
	}

	var collect models.Collect
	data_source.Db.Where("goodid = ?", id).Where("uid = ?", uid).Where("state = 3").First(&collect)
	if collect.ID > 0 {
		data_source.Db.Where("goodid = ?", id).Where("uid = ?", uid).Where("state = 3").Delete(&models.Collect{})
	} else {
		var good models.Fanshang
		data_source.Db.Where("id = ?", id).First(&good)
		collectadd := models.Collect{
			Goodid: int64(id),
			Uid:    int64(uid),
			State:  3,
			Name:   good.Name,
			Image:  good.Image,
		}
		data_source.Db.Create(&collectadd)
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return
}

type FanshanggoodsRBody struct {
	Data       []models.Fanshanggoodsql `json:"data"`
	PageNo     int                      `json:"pageNo"`
	PageSize   int                      `json:"pageSize"`
	TotalCount int64                    `json:"totalCount"`
	TotalPage  int64                    `json:"totalPage"`
}

type FanshanggoodsBody struct {
	Page     int   `json:"page"`
	Pagesize int   `json:"pagesize"`
	ID       int64 `json:"id" gorm:"id"`
}

func Fanshanggoods(ctx *gin.Context) {
	request := FanshanggoodsBody{}
	ctx.ShouldBind(&request)
	id := request.ID
	//currentPage := request.Page
	//pageSize := request.Pagesize
	//offsetNum := pageSize * (currentPage - 1)
	//var count int64
	var niudangoodsql []models.Fanshanggoodsql
	data_source.Db.Model(&models.Fanshanggood{}).Select("fanshanggood.*, goods.name, goods.image, goods.price").Joins("left join goods on goods.id = fanshanggood.goodid").Where("fanshanggood.fanshangid = ?", id).Find(&niudangoodsql)

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    niudangoodsql,
		"msg":     "ok",
	})
	return
}

type FanshangbuyBody struct {
	Fanshangid int64  `json:"fanshangid"`
	Uid        int64  `json:"uid"`
	Paystatus  int64  `json:"paystatus"`
	Num        int64  `json:"num"`
	Qudao      string `json:"qudao" gorm:"qudao"`
}

func Fanshangbuy(ctx *gin.Context) {
	request := FanshangbuyBody{}
	ctx.ShouldBind(&request)
	fanshangid := request.Fanshangid
	uid := request.Uid
	paystatus := request.Paystatus
	num := request.Num
	qudao := request.Qudao
	ip := ctx.ClientIP()
	if uid == 0 {
		ctx.JSON(http.StatusOK, gin.H{
			"code":    101,
			"error":   1,
			"success": 400,
			"data":    "on",
			"msg":     "请登录",
		})
		return
	}

	var fanshang models.Fanshang
	data_source.Db.Where("id = ?", fanshangid).First(&fanshang)
	if fanshang.ID == 0 {
		ctx.JSON(http.StatusOK, gin.H{
			"code":    101,
			"error":   1,
			"success": 400,
			"data":    "on",
			"msg":     "请选择正确一番赏",
		})
		return
	}
	var user models.User
	data_source.Db.Where("id = ?", uid).First(&user)

	if fanshang.Liushui > 0 {
		if fanshang.Classify == 1 {
			var userpriceday []models.Userdayprice
			//startOfToday := time.Now().Truncate(24 * time.Hour)
			startTimestamp := getTodayMidnightTimestamp()
			data_source.Db.Where("uid = ?", uid).Where("addtime = ?", startTimestamp).Find(&userpriceday)

			var liushui float64
			for _, l := range userpriceday {
				liushui = liushui + l.Price
			}

			if fanshang.Liushui > liushui {
				ctx.JSON(http.StatusOK, gin.H{
					"code":    101,
					"error":   1,
					"success": 400,
					"data":    "on",
					"msg":     "今日流水不足",
				})
				return
			}
		} else if fanshang.Classify == 2 {
			if fanshang.Liushui > float64(user.Integral) {
				ctx.JSON(http.StatusOK, gin.H{
					"code":    101,
					"error":   1,
					"success": 400,
					"data":    "on",
					"msg":     "积分不足",
				})
				return
			}
		}
	}
	if fanshang.Daynum > 0 {
		inttime, endtime := getCurrentdayStartAndEnd()
		var fanshangbuyorderdaynum int64
		data_source.Db.Model(&models.Orderfanshang{}).Where("uid = ?", uid).Where("addtime >= ?", inttime).Where("addtime < ?", endtime).Where("fanshangid = ?", fanshangid).Count(&fanshangbuyorderdaynum)
		if fanshangbuyorderdaynum >= fanshang.Daynum {
			ctx.JSON(http.StatusOK, gin.H{
				"code":    101,
				"error":   1,
				"success": 400,
				"data":    "on",
				"msg":     "该赏品每天最多购买" + utils.Int64string(fanshang.Daynum) + "次",
			})
			return
		}

	}

	if fanshang.Usernum > 0 {
		var fanshangbuyordernum int64
		data_source.Db.Model(&models.Orderfanshang{}).Debug().Where("uid = ?", uid).Where("fanshangid = ?", fanshangid).Count(&fanshangbuyordernum)

		if fanshangbuyordernum >= fanshang.Usernum {
			ctx.JSON(http.StatusOK, gin.H{
				"code":    101,
				"error":   1,
				"success": 400,
				"data":    "on",
				"msg":     "该赏品最多购买" + utils.Int64string(fanshang.Usernum) + "次",
			})
			return
		}
	}

	var fanshangprice float64
	if num == 1 {
		fanshangprice = fanshang.Price
	} else if num == 5 {
		fanshangprice = fanshang.Fiveprice
	} else if num == 10 {
		fanshangprice = fanshang.Tenprice
	}

	if user.ID == 0 {
		ctx.JSON(http.StatusOK, gin.H{
			"code":    400,
			"error":   1,
			"success": 400,
			"data":    "on",
			"msg":     "用户不存在",
		})
		return
	}
	if fanshang.Classify == 2 {
		if float64(user.Integral) < fanshangprice {
			ctx.JSON(http.StatusOK, gin.H{
				"code":    400,
				"error":   1,
				"success": 400,
				"data":    "on",
				"msg":     "积分不足",
			})
			return
		}

		orderno := Generateto(time.Time{})
		orderadd := models.Orderfanshang{
			Uid:        uid,
			Fanshangid: fanshangid,
			Orderno:    orderno,
			Addtime:    time.Now().Unix(),
			Status:     2,
			Num:        num,
			Price:      fanshangprice,
			Paystatus:  5,
			Choujiang:  1,
			Qudao:      qudao,
		}
		data_source.Db.Create(&orderadd)
		data_source.Db.Model(&models.User{}).Where("id = ?", uid).Update("integral", float64(user.Integral)-fanshangprice)

		userorder := models.Userorder{
			Uid:       uid,
			Addtime:   time.Now().Unix(),
			State:     3,
			Paystatus: 6,
			Price:     fanshangprice,
			Orderid:   orderadd.ID,
		}
		data_source.Db.Create(&userorder)
		userintegral := models.Userintegral{
			Uid:        uid,
			Addtime:    time.Now().Unix(),
			State:      2,
			Title:      "一番赏",
			Integral:   int64(fanshangprice),
			Syintegral: user.Integral - int64(fanshangprice),
		}
		data_source.Db.Create(&userintegral)
		ctx.JSON(http.StatusOK, gin.H{
			"code":    0,
			"error":   0,
			"success": 200,
			"data":    orderadd.ID,
			"msg":     "ok",
		})
		return

	} else {

		if paystatus == 3 {
			if user.Daibi < fanshangprice {
				ctx.JSON(http.StatusOK, gin.H{
					"code":    400,
					"error":   1,
					"success": 400,
					"data":    "on",
					"msg":     "矿石不足",
				})
				return
			}
		}

		orderno := Generateto(time.Time{})
		orderadd := models.Orderfanshang{
			Uid:        uid,
			Fanshangid: fanshangid,
			Orderno:    orderno,
			Addtime:    time.Now().Unix(),
			Status:     1,
			Num:        num,
			Price:      fanshangprice,
			Paystatus:  paystatus,
			Choujiang:  1,
		}
		data_source.Db.Create(&orderadd)

		//startOfToday := time.Now().Truncate(24 * time.Hour)
		startTimestamp := getTodayMidnightTimestamp()
		if paystatus == 1 {
			aliRsp := Goodalipay(orderno, int64(fanshangprice*100))

			ctx.JSON(http.StatusOK, gin.H{
				"code":    0,
				"error":   0,
				"success": 200,
				"data":    aliRsp,
				"msg":     "ok",
			})
			return
		} else if paystatus == 2 {
			ctx.JSON(http.StatusOK, gin.H{
				"code":    0,
				"error":   0,
				"success": 200,
				"data":    orderadd.ID,
				"msg":     "ok",
			})
			return
		} else if paystatus == 3 {

			data_source.Db.Model(&models.Orderfanshang{}).Where("id = ?", orderadd.ID).Update("status", 2)
			data_source.Db.Model(&models.User{}).Where("id = ?", uid).Update("daibi", user.Daibi-fanshangprice)
			var userdayprice models.Userdayprice
			data_source.Db.Where("uid = ?", uid).Where("addtime = ?", startTimestamp).First(&userdayprice)
			if userdayprice.ID == 0 {
				userdaypriceadd := models.Userdayprice{
					Uid:     uid,
					Addtime: startTimestamp,
					Price:   fanshangprice,
				}
				data_source.Db.Create(&userdaypriceadd)
			} else {
				data_source.Db.Model(&models.Userdayprice{}).Where("id = ?", userdayprice.ID).Update("price", userdayprice.Price+fanshangprice)
			}
			userdaibi := models.Userdaibi{
				Uid:     uid,
				Status:  2,
				Addtime: time.Now().Unix(),
				Daibi:   fanshangprice,
				Title:   "一番赏",
				State:   6,
				Sydaibi: user.Daibi - fanshangprice,
			}
			data_source.Db.Create(&userdaibi)

			userorder := models.Userorder{
				Uid:       uid,
				Addtime:   time.Now().Unix(),
				State:     3,
				Paystatus: paystatus,
				Price:     fanshangprice,
				Orderid:   orderadd.ID,
			}
			data_source.Db.Create(&userorder)
			//fmt.Println(orderadd)

			Zhongjiangfs(orderadd)

			//判断是否升级vip
			service.Vipsj(user, fanshangprice)
			ctx.JSON(http.StatusOK, gin.H{
				"code":    0,
				"error":   0,
				"success": 200,
				"data":    orderadd.ID,
				"msg":     "ok",
			})
			return
		} else if paystatus == 4 {
			data := Wechatpayxcxyfs(orderno, fanshangprice, user, ip, orderadd.ID)
			ctx.JSON(http.StatusOK, gin.H{
				"code":    0,
				"error":   0,
				"success": 200,
				"data":    data,
				"msg":     "ok",
			})
			return
		}
	}

}

func Zhongjiangfs(order models.Orderfanshang) {

	var integral int64
	var zhuanpan models.Zhuanpan
	data_source.Db.Where("fanshangid = ?", order.Fanshangid).Where("state = 1").First(&zhuanpan)
	var fanshang models.Fanshang
	data_source.Db.Where("id = ?", order.Fanshangid).First(&fanshang)

	var fanshanggoods []models.Fanshanggood
	var shangjuan models.Shangjuan

	if zhuanpan.ID > 0 {
		dengji := strings.Split(zhuanpan.Dengji, ",")
		if dengji[0] == "" {
			data_source.Db.Where("fanshangid = ?", order.Fanshangid).Find(&fanshanggoods)
		} else {
			data_source.Db.Where("fanshangid = ?", order.Fanshangid).Where("classify not in (?)", dengji).Find(&fanshanggoods)
		}
		if zhuanpan.Classify == 2 {
			data_source.Db.Where("id = ?", zhuanpan.Shangjuanid).First(&shangjuan)
		}
	} else {
		data_source.Db.Debug().Where("fanshangid = ?", order.Fanshangid).Find(&fanshanggoods)
	}
	//fmt.Println(fanshanggoods)
	//return
	var anum int64
	var bnum int64
	var cnum int64
	var dnum int64
	for _, f := range fanshanggoods {
		if f.Classify == 1 {
			anum = anum + f.Num
		}
		if f.Classify == 2 {
			bnum = bnum + f.Num
		}
		if f.Classify == 3 {
			cnum = cnum + f.Num
		}
		if f.Classify == 4 {
			dnum = dnum + f.Num
		}
	}
	var abili float64
	var bbili float64
	var cbili float64
	var dbili float64

	var goodidarr []int64
	for k, v := range fanshanggoods {
		if v.Classify == 1 {
			abili = float64(v.Num) / float64(anum)
			fanshanggoods[k].Bili = fanshang.Ashang * 100 * abili
		} else if v.Classify == 2 {
			bbili = float64(v.Num) / float64(bnum)
			fanshanggoods[k].Bili = fanshang.Bshang * 100 * bbili
		} else if v.Classify == 3 {
			cbili = float64(v.Num) / float64(cnum)
			fanshanggoods[k].Bili = fanshang.Cshang * 100 * cbili
		} else if v.Classify == 4 {
			dbili = float64(v.Num) / float64(dnum)
			fanshanggoods[k].Bili = fanshang.Dshang * 100 * dbili
		}
		goodidarr = append(goodidarr, v.Goodid)
	}

	var goods []models.Goods
	data_source.Db.Where("id in (?)", goodidarr).Where("status = 1").Find(&goods)

	now := time.Now()
	zeroToday := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()).Unix()
	var user models.User
	data_source.Db.Where("id = ?", order.Uid).First(&user)
	var ordergoods []models.Orderfanshanggood
	var usershangjuans []models.Usershangjuan

	for i := 0; i < int(order.Num); i++ {
		goodid, dengji := service.GetResultfs(fanshanggoods)

		for _, good := range goods {
			if goodid == good.ID {
				orderniudangood := models.Orderfanshanggood{
					Uid:             order.Uid,
					Goodid:          goodid,
					Goodname:        good.Name,
					Goodimage:       good.Image,
					Goodmojing:      good.Mojing,
					Goodprice:       good.Price,
					Orderfanshangid: int64(order.ID),
					Addtime:         zeroToday,
					Num:             1,
					Dengji:          dengji,
					State:           1,
				}
				ordergoods = append(ordergoods, orderniudangood)
				service.Gooduser(user, good, 1, 3, 1, 0, order.ID)
			}
		}
		addtime := time.Now().Unix()
		if zhuanpan.ID > 0 {
			zhongjian := service.CalculateProbability(int64(zhuanpan.Bili * 100))
			if zhongjian == true {
				if zhuanpan.Classify == 1 {
					integral = integral + zhuanpan.Integral*zhuanpan.Num
				} else if zhuanpan.Classify == 2 {
					if shangjuan.ID > 0 {
						var endtime int64
						if shangjuan.Day > 0 {
							endtime = addtime + shangjuan.Day*864000
						}

						for iu := 0; iu < int(zhuanpan.Num); iu++ {

							usershangjuan := models.Usershangjuan{
								Uid:             order.Uid,
								Addtime:         addtime,
								Day:             shangjuan.Day,
								Name:            shangjuan.Name,
								Image:           shangjuan.Image,
								Daibi:           shangjuan.Daibi,
								Num:             shangjuan.Num,
								Userdaibi:       shangjuan.Userdaibi,
								Status:          1,
								Orderfanshangid: int64(order.ID),
								Endtime:         endtime,
								Shangjuanid:     shangjuan.ID,
								State:           1,
							}
							usershangjuans = append(usershangjuans, usershangjuan)
						}
					}

				}
			}
		}
	}

	data_source.Db.Create(&ordergoods)
	data_source.Db.Model(&models.Orderfanshang{}).Where("id = ?", order.ID).Update("choujiang", 2)
	if len(usershangjuans) > 0 {
		data_source.Db.Create(&usershangjuans)
	}
	if integral > 0 {
		orderfanshangintegral := models.Orderfanshangintegral{
			Uid:             order.Uid,
			Integral:        integral,
			Orderfanshangid: int64(order.ID),
		}
		data_source.Db.Create(&orderfanshangintegral)

		userintegral := models.Userintegral{
			Uid:        order.Uid,
			Addtime:    time.Now().Unix(),
			State:      1,
			Title:      "一番赏抽中隐藏积分",
			Integral:   integral,
			Syintegral: user.Integral + integral,
		}
		data_source.Db.Create(&userintegral)
		data_source.Db.Model(&models.User{}).Where("id = ?", order.Uid).Update("integral", user.Integral+integral)

	}
}

type ChoujiangfRBody struct {
	Orderfanshanggood []models.Orderfanshanggood `json:"orderfanshanggood"`
	Usershangjuan     []models.Usershangjuan     `json:"usershangjuan"`
	Integral          int64                      `json:"integral" gorm:"integral"`
	Status            int64                      `json:"status" gorm:"status"` //1积分 2赏卷 3无隐藏奖励
}

func Choujiangfs(ctx *gin.Context) {
	request := GoodsBody{}
	ctx.ShouldBind(&request)
	id := request.ID
	var order models.Orderfanshang
	data_source.Db.Where("id = ?", id).First(&order)

	var integral int64
	var zhuanpan models.Zhuanpan
	data_source.Db.Where("fanshangid = ?", order.Fanshangid).Where("state = 1").First(&zhuanpan)

	if order.Status == 1 {
		ctx.JSON(http.StatusOK, gin.H{
			"code":    400,
			"error":   1,
			"success": 400,
			"data":    "on",
			"msg":     "请支付",
		})
		return
	}

	if order.Choujiang == 2 {
		var ordergoods []models.Orderfanshanggood
		data_source.Db.Where("orderfanshangid = ?", id).Find(&ordergoods)
		var fanshangjf models.Orderfanshangintegral
		var shangjuans []models.Usershangjuan
		if zhuanpan.ID > 0 {
			if zhuanpan.Classify == 1 {
				data_source.Db.Where("orderfanshangid = ?", id).Where("state = 1").First(&fanshangjf)
				integral = fanshangjf.Integral

				if fanshangjf.ID > 0 {
					integral = fanshangjf.Integral
					orderniudangjifen := models.Orderfanshanggood{
						Goodname:  "积分",
						Num:       integral,
						Goodimage: "http://interstellar-tide-play.oss-cn-shanghai.aliyuncs.com/shequ/2024-10-27/1730020800积分@3x.png",
						State:     2,
					}
					ordergoods = append(ordergoods, orderniudangjifen)
				}

			} else if zhuanpan.Classify == 2 {
				data_source.Db.Where("orderfanshangid = ?", id).Where("state = 1").Find(&shangjuans)
				if len(shangjuans) > 0 {
					var sjnum int64
					for _, s := range shangjuans {
						sjnum = sjnum + s.Num
					}
					orderniudangsj := models.Orderfanshanggood{
						Goodname:  "赏券",
						Num:       sjnum,
						Goodimage: "http://interstellar-tide-play.oss-cn-shanghai.aliyuncs.com/shequ/2024-10-27/1730020843赏券@3x.png",
						State:     3,
					}
					ordergoods = append(ordergoods, orderniudangsj)
				}
			}

		}

		ctx.JSON(http.StatusOK, gin.H{
			"code":    0,
			"error":   0,
			"success": 200,
			"data":    ordergoods,
			"msg":     "ok",
		})
		return
	} else {
		var fanshang models.Fanshang
		data_source.Db.Where("id = ?", order.Fanshangid).First(&fanshang)

		var fanshanggoods []models.Fanshanggood
		var shangjuan models.Shangjuan
		if zhuanpan.ID > 0 {
			dengji := strings.Split(zhuanpan.Dengji, ",")
			if dengji[0] == "" {
				data_source.Db.Where("fanshangid = ?", order.Fanshangid).Find(&fanshanggoods)
			} else {
				data_source.Db.Where("fanshangid = ?", order.Fanshangid).Where("classify not in (?)", dengji).Find(&fanshanggoods)
			}
			if zhuanpan.Classify == 2 {

				data_source.Db.Where("id = ?", zhuanpan.Shangjuanid).First(&shangjuan)
			}
		} else {
			data_source.Db.Where("fanshangid = ?", order.Fanshangid).Find(&fanshanggoods)
		}

		var anum int64
		var bnum int64
		var cnum int64
		var dnum int64
		for _, f := range fanshanggoods {
			if f.Classify == 1 {
				anum = anum + f.Num
			}
			if f.Classify == 2 {
				bnum = bnum + f.Num
			}
			if f.Classify == 3 {
				cnum = cnum + f.Num
			}
			if f.Classify == 4 {
				dnum = dnum + f.Num
			}
		}
		var abili float64
		var bbili float64
		var cbili float64
		var dbili float64

		var goodidarr []int64
		for k, v := range fanshanggoods {
			if v.Classify == 1 {
				abili = float64(v.Num) / float64(anum)
				fanshanggoods[k].Bili = fanshang.Ashang * 100 * abili
			} else if v.Classify == 2 {
				bbili = float64(v.Num) / float64(bnum)
				fanshanggoods[k].Bili = fanshang.Bshang * 100 * bbili
			} else if v.Classify == 3 {
				cbili = float64(v.Num) / float64(cnum)
				fanshanggoods[k].Bili = fanshang.Cshang * 100 * cbili
			} else if v.Classify == 4 {
				dbili = float64(v.Num) / float64(dnum)
				fanshanggoods[k].Bili = fanshang.Dshang * 100 * dbili
			}
			goodidarr = append(goodidarr, v.Goodid)
		}

		var goods []models.Goods
		data_source.Db.Where("id in (?)", goodidarr).Where("status = 1").Find(&goods)

		now := time.Now()
		zeroToday := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()).Unix()
		var user models.User
		data_source.Db.Where("id = ?", order.Uid).First(&user)
		var ordergoods []models.Orderfanshanggood
		var usershangjuans []models.Usershangjuan
		for i := 0; i < int(order.Num); i++ {
			goodid, dengji := service.GetResultfs(fanshanggoods)
			for _, good := range goods {
				if goodid == good.ID {
					orderniudangood := models.Orderfanshanggood{
						Uid:             order.Uid,
						Goodid:          goodid,
						Goodname:        good.Name,
						Goodimage:       good.Image,
						Goodmojing:      good.Mojing,
						Goodprice:       good.Price,
						Orderfanshangid: int64(id),
						Addtime:         zeroToday,
						Num:             1,
						Dengji:          dengji,
						State:           1,
					}
					ordergoods = append(ordergoods, orderniudangood)
					service.Gooduser(user, good, 1, 3, 1, 0, order.ID)
				}
			}
			addtime := time.Now().Unix()
			if zhuanpan.ID > 0 {
				zhongjian := service.CalculateProbability(int64(zhuanpan.Bili * 100))
				if zhongjian == true {
					if zhuanpan.Classify == 1 {
						integral = integral + zhuanpan.Integral*zhuanpan.Num
					} else {

						var endtime int64
						if shangjuan.Day > 0 {
							endtime = addtime + shangjuan.Day*864000
						}
						var sjnum int64
						for iu := 0; iu < int(zhuanpan.Num); iu++ {

							usershangjuan := models.Usershangjuan{
								Uid:             order.Uid,
								Addtime:         addtime,
								Day:             shangjuan.Day,
								Name:            shangjuan.Name,
								Image:           shangjuan.Image,
								Daibi:           shangjuan.Daibi,
								Num:             shangjuan.Num,
								Userdaibi:       shangjuan.Userdaibi,
								Status:          1,
								Orderfanshangid: int64(id),
								Endtime:         endtime,
								Shangjuanid:     shangjuan.ID,
								State:           1,
							}
							usershangjuans = append(usershangjuans, usershangjuan)
							sjnum = sjnum + shangjuan.Num
						}
						orderniudangsj := models.Orderfanshanggood{
							Goodname:  "赏券",
							Num:       sjnum,
							Goodimage: "http://interstellar-tide-play.oss-cn-shanghai.aliyuncs.com/shequ/2024-10-27/1730020843赏券@3x.png",
							State:     3,
						}
						ordergoods = append(ordergoods, orderniudangsj)
					}
				}
			}
		}
		data_source.Db.Create(&ordergoods)
		data_source.Db.Model(&models.Orderfanshang{}).Where("id = ?", id).Update("choujiang", 2)
		if len(usershangjuans) > 0 {
			data_source.Db.Create(&usershangjuans)
		}
		if integral > 0 {
			orderfanshangintegral := models.Orderfanshangintegral{
				Uid:             order.Uid,
				Integral:        integral,
				Orderfanshangid: int64(id),
				State:           1,
			}
			data_source.Db.Create(&orderfanshangintegral)

			userintegral := models.Userintegral{
				Uid:        order.Uid,
				Addtime:    time.Now().Unix(),
				State:      1,
				Title:      "一番赏抽中隐藏积分",
				Integral:   integral,
				Syintegral: user.Integral + integral,
			}
			data_source.Db.Create(&userintegral)
			data_source.Db.Model(&models.User{}).Where("id = ?", order.Uid).Update("integral", user.Integral+integral)
			orderniudangjifen := models.Orderfanshanggood{
				Goodname:  "积分",
				Num:       integral,
				Goodimage: "http://interstellar-tide-play.oss-cn-shanghai.aliyuncs.com/shequ/2024-10-27/1730020800积分@3x.png",
				State:     2,
			}
			ordergoods = append(ordergoods, orderniudangjifen)
		}

		ctx.JSON(http.StatusOK, gin.H{
			"code":    0,
			"error":   0,
			"success": 200,
			"data":    ordergoods,
			"msg":     "ok",
		})
		return
	}

}

func Fanshangsq(ctx *gin.Context) {
	request := GoodsBody{}
	ctx.ShouldBind(&request)
	id := request.ID
	var orderfanshangs []models.Orderfanshang
	data_source.Db.Where("fanshangid = ?", id).Find(&orderfanshangs)
	var orderidarr []int64
	for _, v := range orderfanshangs {
		orderidarr = append(orderidarr, v.ID)
	}
	//fmt.Println(orderidarr)
	var orderfanshangood []models.Orderfanshanggoodsql
	data_source.Db.Model(&models.Orderfanshanggood{}).Select("orderfanshanggood.*, user.nickname, user.logo").Joins("left join user on user.id = orderfanshanggood.uid").Where("orderfanshanggood.orderfanshangid in (?)", orderidarr).Limit(10).Order("goodprice desc").Find(&orderfanshangood)

	var orderfanshangoodtwo []models.Orderfanshanggoodsql
	for _, o := range orderfanshangood {
		cunzai := 1
		for _, ot := range orderfanshangoodtwo {
			if o.Uid == ot.Uid {
				cunzai = 2
			}
		}
		if cunzai == 1 {
			orderfanshangoodtwo = append(orderfanshangoodtwo, o)
		}
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    orderfanshangoodtwo,
		"msg":     "ok",
	})
	return
}

type BuylistRBody struct {
	Name     string `json:"name" gorm:"name"`
	Image    string `json:"image" gorm:"image"`
	Addtime  int64  `json:"addtime" gorm:"addtime"`
	Classify int64  `json:"classify" gorm:"classify"`
	Goodname string `json:"goodname" gorm:"goodname"`
}
type BuyclassifymsgRBody struct {
	Ashang []BuylistRBody `json:"ashang" gorm:"ashang"`
	Bshang []BuylistRBody `json:"bshang" gorm:"bshang"`
	Cshang []BuylistRBody `json:"cshang" gorm:"cshang"`
	Dshang []BuylistRBody `json:"dshang" gorm:"dshang"`
}

func Fanshangbuys(ctx *gin.Context) {
	request := GoodsBody{}
	ctx.ShouldBind(&request)
	id := request.ID
	var orderfanshangs []models.Orderfanshang
	data_source.Db.Where("fanshangid = ?", id).Find(&orderfanshangs)
	var orderidarr []int64
	for _, v := range orderfanshangs {
		orderidarr = append(orderidarr, v.ID)
	}
	var orderfanshangood []models.Orderfanshanggoodsql
	data_source.Db.Model(&models.Orderfanshanggood{}).Select("orderfanshanggood.*, user.nickname, user.logo").Joins("left join user on user.id = orderfanshanggood.uid").Where("orderfanshanggood.orderfanshangid in (?)", orderidarr).Limit(40).Order("id desc").Find(&orderfanshangood)
	var ashangs []BuylistRBody
	var bshangs []BuylistRBody
	var cshangs []BuylistRBody
	var dshangs []BuylistRBody

	for _, or := range orderfanshangood {
		if or.Dengji == 1 {
			ashang := BuylistRBody{
				Name:     or.Nickname,
				Image:    or.Logo,
				Addtime:  or.Addtime,
				Classify: 1,
				Goodname: or.Goodname,
			}
			ashangs = append(ashangs, ashang)
		}
		if or.Dengji == 2 {
			bshang := BuylistRBody{
				Name:     or.Nickname,
				Image:    or.Logo,
				Addtime:  or.Addtime,
				Classify: 2,
				Goodname: or.Goodname,
			}
			bshangs = append(bshangs, bshang)
		}
		if or.Dengji == 3 {
			cshang := BuylistRBody{
				Name:     or.Nickname,
				Image:    or.Logo,
				Addtime:  or.Addtime,
				Classify: 3,
				Goodname: or.Goodname,
			}
			cshangs = append(cshangs, cshang)
		}
		if or.Dengji == 4 {
			dshang := BuylistRBody{
				Name:     or.Nickname,
				Image:    or.Logo,
				Addtime:  or.Addtime,
				Classify: 4,
				Goodname: or.Goodname,
			}
			dshangs = append(dshangs, dshang)
		}
	}
	data := BuyclassifymsgRBody{
		Ashang: ashangs,
		Bshang: bshangs,
		Cshang: cshangs,
		Dshang: dshangs,
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    data,
		"msg":     "ok",
	})
	return
}

func Fanshangzj(ctx *gin.Context) {
	request := GoodsBody{}
	ctx.ShouldBind(&request)
	id := request.ID
	var orderfanshangs []models.Orderfanshang
	data_source.Db.Where("fanshangid = ?", id).Find(&orderfanshangs)
	var zhuanpan models.Zhuanpan
	data_source.Db.Where("state = 1").Where("fanshangid = ?", id).First(&zhuanpan)

	dengjiarr := strings.Split(zhuanpan.Piaoping, ",")

	var orderidarr []int64
	for _, v := range orderfanshangs {
		orderidarr = append(orderidarr, v.ID)
	}
	//fmt.Println(orderidarr)
	var orderfanshangood []models.Orderfanshanggoodsql
	data_source.Db.Model(&models.Orderfanshanggood{}).Select("orderfanshanggood.*, user.nickname").Joins("left join user on user.id = orderfanshanggood.uid").Where("orderfanshanggood.orderfanshangid in (?)", orderidarr).Where("orderfanshanggood.dengji in (?)", dengjiarr).Limit(10).Order("goodprice desc").Find(&orderfanshangood)

	for k, o := range orderfanshangood {

		runes := []rune(o.Nickname)
		strval := string(runes[:1])
		strval = strval + "***"
		orderfanshangood[k].Nickname = strval
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    orderfanshangood,
		"msg":     "ok",
	})
	return
}

func Piaoping(ctx *gin.Context) {
	request := GoodsBody{}
	ctx.ShouldBind(&request)

	var orderfanshangood []models.Orderfanshanggoodsql
	data_source.Db.Model(&models.Orderfanshanggood{}).Select("orderfanshanggood.*, user.nickname, user.logo").Joins("left join user on user.id = orderfanshanggood.uid").Where("orderfanshanggood.dengji = 1 or orderfanshanggood.dengji = 2").Where("orderfanshanggood.addtime >= ?", time.Now().Unix()-86400*3).Limit(10).Order("orderfanshanggood.goodprice desc").Find(&orderfanshangood)

	for k, o := range orderfanshangood {

		runes := []rune(o.Nickname)
		strval := string(runes[:1])
		strval = strval + "***"
		orderfanshangood[k].Nickname = strval
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    orderfanshangood,
		"msg":     "ok",
	})
	return
}
func Fanshangjiashuju(orderfanshangood []models.Orderfanshanggoodsql) (new []models.Orderfanshanggoodsql) {

	orderfanshangood1 := models.Orderfanshanggoodsql{
		Nickname: "许咩",
		Logo:     "https://thirdwx.qlogo.cn/mmopen/vi_32/PiajxSqBRaELRykvbPo8bm2EzdOwEJJmnLKmq7gTPpibIVPEmLAL6kz51sRpWEV8wYAapot8XntggOY9KZcIeS4fcq8V9LWRqjibicNXHPiby7ZDe9liaC1pvo5w/132",
		Dengji:   1,
	}
	orderfanshangood = append(orderfanshangood, orderfanshangood1)

	orderfanshangood2 := models.Orderfanshanggoodsql{
		Nickname: "空笑",
		Logo:     "https://thirdwx.qlogo.cn/mmopen/vi_32/zsbbK8iaibreWYGLjic0Wc4ibU8B6oc07ViabIFRib4kDGrohNuhRkhibU1eYwsRcNpxG4EegsqU3kugapkVKibmIPIPAQ/132",
		Dengji:   1,
	}
	orderfanshangood = append(orderfanshangood, orderfanshangood2)

	orderfanshangood3 := models.Orderfanshanggoodsql{
		Nickname: "AA再生资源废钢设备 刘19550831131",
		Logo:     "https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTLmFDia64wXwzjnVLf008UsHhXQFEtq0w7ibmgXYmNy0OBeoA1PquwFtLNWeaw7j5L1pEwA0zh8KJRQ/132",
		Dengji:   2,
	}
	orderfanshangood = append(orderfanshangood, orderfanshangood3)

	orderfanshangood4 := models.Orderfanshanggoodsql{
		Nickname: "豫工起重机",
		Logo:     "http://thirdwx.qlogo.cn/mmopen/vCFegP3BQCf9DM4JCmbok3oOibibc5AZIH9X6BegCYicOpAof6q0y81JJwo0jibvnMtO3VXWJB69MHwrHWHvJv3kEiayiaSy6DYKVL/132",
		Dengji:   2,
	}
	orderfanshangood = append(orderfanshangood, orderfanshangood4)
	return orderfanshangood

}
